#include "system.h"

System* System::GetInstance()
{
	static System instance;
	return &instance;
}

void System::Initialize()
{
	LogManager::Initialize("logs/");
	LogManager::LogLine("Starting game.");

	// Initialize Allegro.
	al_init();
	al_init_image_addon();
	al_init_primitives_addon();
	al_init_font_addon();
	al_init_ttf_addon();

	al_install_mouse();
	al_install_keyboard();

	// Create the display.
	al_set_new_display_flags(ALLEGRO_WINDOWED);
	m_display = al_create_display(1024, 768);
	Screen::GetInstance()->SetDimensions(1024, 768);

	m_game = new GameEngine;

	//DEBUG
	bool is_server = false;
	std::string input;
	std::cout << "Server (y/n) ";
	std::cin >> input;
	if (input == "y")
		is_server = true;
	std::cout << "\nName: ";
	std::cin >> input;
	//END DEBUG

	LobbyState* state = new LobbyState(m_game);
	state->Init(is_server, input);

	//TestState* state = new TestState(m_game);
	//state->Init();

	m_game->SetNextState(state);
}

void System::Run()
{
	while (true)
	{
		m_game->CheckState();

		m_game->HandleInput();
		m_game->Update();
		m_game->Draw();

		if (m_game->end_game())
		{
			break;
		}
	}

	Shutdown();
}

void System::Shutdown()
{
	LogManager::LogLine("Shutting down...");

	// TODO: Delete all bitmaps from allegro resource manager.

	delete m_game;
	al_destroy_display(m_display);

	al_uninstall_mouse();
	al_uninstall_keyboard();

	al_shutdown_image_addon();
	al_shutdown_primitives_addon();
	al_shutdown_font_addon();

	// Everything goes well if we do not call ttf shutdown.
	// Why does this cause an error?
	//al_shutdown_ttf_addon();

	al_uninstall_system();

	LogManager::LogLine("Shut down. Exiting...");
	LogManager::Close();
}